package com.apes.fn.crm.ReturnVisit.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.crm.ReturnVisit.model.VisitCustomerRoleExpand;
import com.apes.fn.crm.ReturnVisit.repository.VisitCustomerRoleExpandRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("visitCustomerRoleExpandService")
public class VisitCustomerRoleExpandService extends DomainService {

    @Autowired
    VisitCustomerRoleExpandRepository visitCustomerRoleExpandRepository;

    /***
     * 创建
     */
    public VisitCustomerRoleExpand create(SimpleRequest request) {
        VisitCustomerRoleExpand visitCustomerRoleExpand = request.getO(VisitCustomerRoleExpand.class);
        return visitCustomerRoleExpandRepository.saveAndFlush(visitCustomerRoleExpand);
    }

    /***
     * 修改
     */
    public VisitCustomerRoleExpand update(SimpleRequest request) {
        isValid(request, visitCustomerRoleExpandRepository);
        VisitCustomerRoleExpand visitCustomerRoleExpand = request.getO(VisitCustomerRoleExpand.class);
        return visitCustomerRoleExpandRepository.saveAndFlush(visitCustomerRoleExpand);
    }

    /***
     * 删除
     */
    public String delete(SimpleRequest request) {
        isValid(request, visitCustomerRoleExpandRepository);
        VisitCustomerRoleExpand visitCustomerRoleExpand = request.getO(VisitCustomerRoleExpand.class);
        visitCustomerRoleExpandRepository.delete(visitCustomerRoleExpand);
        return "删除成功！";
    }


    /***
     * 查询所有的会员等级扩展表
     */
    public Map findAll(SimpleRequest request) {
        List<VisitCustomerRoleExpand> filters = parseQuery(query(), request);
        if (!filters.isEmpty()) {
            return MapUtil.mapper(
                    "total", filters.size(),
                    "pages", 1,
                    "size", 20,
                    "elements", filters.size(),
                    "page", 0,
                    "content", filters
            );
        } else {
            return MapUtil.mapper(
                    "total", 0,
                    "pages", 0,
                    "size", 20,
                    "elements", 0,
                    "page", 0,
                    "content", new ArrayList()
            );
        }
    }

    /***
     * 查询并拼接数据（App 以及 本地数据）   */
    private List<VisitCustomerRoleExpand> query() {
        JSONObject response = null;
        try {
            Map param = getQueryParams("v1/user/user-role/index");
            response = JSONObject.parseObject(this.invoke("pi.app.ext", param));
        } catch (Exception e) {

        }

        List<VisitCustomerRoleExpand> visitCustomerRoleExpands = new ArrayList();
        if (response != null && response.getBooleanValue("success") &&
                response.get("data") != null && response.getJSONArray("data").size() > 0) {
            JSONArray tempArray = response.getJSONArray("data");
            if (visitCustomerRoleExpands.isEmpty()) {
                tempArray.stream()
                        .filter(obj -> ((JSONObject) obj).get("name") != null && !((JSONObject) obj).getString("name").equals(""))
                        .forEach(obj -> {
                            JSONObject tempJson = (JSONObject) obj;
                            VisitCustomerRoleExpand visitCustomerRoleExpand = visitCustomerRoleExpandRepository.findOne(
                                    JpaDsl.toCriteriaByEq("customerRoleId", tempJson.getString("id"))
                            ).orElse(null);

                            if (visitCustomerRoleExpand == null) {
                                visitCustomerRoleExpand = new VisitCustomerRoleExpand();
                                visitCustomerRoleExpand.setCustomerRoleId(tempJson.getString("id"));
                                visitCustomerRoleExpand.setCustomerRoleName(tempJson.getString("name"));
                                visitCustomerRoleExpand.setVisitSign(true);
                                visitCustomerRoleExpand = visitCustomerRoleExpandRepository.save(visitCustomerRoleExpand);
                            } else {
                                visitCustomerRoleExpand.setCustomerRoleName(tempJson.getString("name"));
                            }
                            visitCustomerRoleExpands.add(visitCustomerRoleExpand);

                        });
            }
            return visitCustomerRoleExpands;
        } else {
            return visitCustomerRoleExpandRepository.findAll();
        }

    }

    /***
     * 组装查询参数(app)
     * @param method
     * @return
     */

    private Map getQueryParams(String method) {
        return MapUtil.mapper(
                "body", new JSONObject(),
                "headers", MapUtil.mapper(
                        "method", method,
                        "action", "get"
                )
        );
    }

    private List<VisitCustomerRoleExpand> parseQuery(List<VisitCustomerRoleExpand> items, SimpleRequest request) {
//        {"condition":[{"field":"id","operator":"EQ","value":"10"},{"field":"name","operator":"EQ","value":"111"}]
        JSONObject tempJson = request.getJO();
        if (tempJson.get("condition") != null && !tempJson.getJSONArray("condition").isEmpty()) {
            JSONArray conditions = tempJson.getJSONArray("condition");
            return items.stream().filter(item -> {
                return conditions.stream().allMatch(condition -> {
                    JSONObject obj = (JSONObject) condition;
                    Map m = Tools.toMap(item);
                    if (obj.getString("operator").equals("EQ"))
                        return obj.getString("value").equals((String) m.get(obj.getString("field")));
                    if (obj.getString("operator").equals("LIKE"))
                        return ((String) m.get(obj.getString("field"))).contains(obj.getString("value"));
                    return false;
                });
            }).collect(Collectors.toList());
        }
        return items;
    }

    /***
     * 通过会员级别编码查询数据
     */
    public VisitCustomerRoleExpand findByCustomerRolelId(String id) {
        return visitCustomerRoleExpandRepository.findOne(JpaDsl.toCriteriaByEq(
                "customerRoleId", id
        )).orElse(null);
    }


    /***
     * 数据是否合法
     * @param request
     * @param repository
     */
    private Model isValid(SimpleRequest request, CustomRepository repository) {
        Model oldModel = (Model) repository.findOne((String) request.get("id"));
        if (oldModel == null) throw new RuntimeException("编码【" + request.get("id") + "】在系统中不存在。");
        if (oldModel.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return oldModel;
    }
}
